import React, {useEffect, useState} from 'react';
import {useNavigate, useParams, useSearchParams} from 'react-router-dom';

import {Box, Button, Container, Stack, TextField, Typography} from '@mui/material';
import CircularProgress from '@mui/material/CircularProgress';
import LoadingButton from '@mui/lab/LoadingButton';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';

import {regInfo, register} from "../api/common/register";

/**
 *
 * url = /register
 *   principal register, create school accompany
 *
 * url = /register/:code                            cat=1
 *   parent register with referrer code
 *   get school info from server by referrer code
 *   if school not found, show error message
 *
 * url = /register?parent={parent_id}               cat=2
 *   child register with parent id
 *
 * url = /register?teacher={school_id}              cat=3
 *   teacher register with school id
 *
 * url = /register?referrer={school_id}             cat=4
 *   referrer register with school id
 *
 * @returns {Element}
 * @constructor
 */
function RegisterPage() {

    const {code} = useParams();

    const [searParams] = useSearchParams();
    const [parent_id] = useState(searParams.get('parent'));
    const [teacher_id] = useState(searParams.get('teacher'));
    const [referrer_id] = useState(searParams.get('referrer'));

    const [parentName, setParentName] = useState('');
    const [roleDesc, setRoleDesc] = useState('');

    const [loading, setLoading] = useState(false);
    const [dialogOpen, setDialogOpen] = useState(false);

    const navigate = useNavigate();

    const [form, setForm] = useState({
        name: '',
        loginId: '',
        password: '',
        role: '',
        school: '',
        schoolId: 0,
        parentId: 0,
        referrerId: 0,
    });

    useEffect(() => {
        document.title = '注册';
    }, []);

    useEffect(() => {
            let cat, reqCode, role, desc;
            if (code) {
                cat = 1
                reqCode = code;
                role = "PARENT";
                desc = "家长";
            } else if (parent_id) {
                cat = 2;
                reqCode = parent_id;
                role = "STUDENT";
                desc = "学生";
            } else if (teacher_id) {
                cat = 3;
                reqCode = teacher_id;
                role = "TEACHER";
                desc = "老师";
            } else if (referrer_id) {
                cat = 4;
                reqCode = referrer_id;
                role = "REFERRER";
                desc = "推广人";
            } else {
                setRoleDesc("校长");
                setForm(prev => ({...prev, role: "PRINCIPAL"}));
                return;
            }

            setRoleDesc(desc);

            regInfo(cat, reqCode).then(
                data => {
                    if (data) {
                        setForm(prev => ({
                            ...prev,
                            school: data.schoolName,
                            schoolId: data.schoolId,
                            referrerId: data.referrerId,
                            role: role,
                            parentId: parent_id || 0,
                            desc: desc,
                        }));
                        setParentName(data.parentName);
                    }
                }
            );
        }, [code, parent_id, referrer_id, teacher_id]
    );

    const handleChange = (event) => {
        const {name, value} = event.target;
        setForm({...form, [name]: value,});
    };

    const handleSubmit = async (event) => {
        event.preventDefault();

        setLoading(true);
        register(form).then(data => {
                setLoading(false);
                if (data) {
                    setDialogOpen(true);
                }
            }
        );
    };

    const handleDialogClose = () => {
        setDialogOpen(false);
    };

    return (<>
        <Dialog open={dialogOpen} onClose={handleDialogClose}>
            <DialogTitle>注册成功</DialogTitle>
            <DialogContent>
                <DialogContentText>
                    你的账号 {form.loginId} 已注册成功，点击登录按钮前往登录
                </DialogContentText>
            </DialogContent>
            <DialogActions>
                <Button onClick={() => navigate('/login')} autoFocus>登录</Button>
            </DialogActions>
        </Dialog>

        <Container maxWidth="xs">
            <Box display="flex" flexDirection="column" justifyContent="center" alignItems="center" minHeight="90vh">
                <Box width="100%" maxWidth={450}>
                    <Stack direction="row" spacing={2} alignItems="baseline">
                        <Typography component="h1" variant="h5">{roleDesc}注册</Typography>
                        <Typography>{
                            form.role === 'PRINCIPAL' ? "校长" :
                                (form.role === 'STUDENT' ? `家长：${parentName}` : form.school)
                        }</Typography>
                    </Stack>

                    <form onSubmit={handleSubmit}>
                        <TextField
                            margin="normal"
                            required
                            fullWidth
                            label="姓名"
                            name="name"
                            value={form.name || ''}
                            onChange={handleChange}
                            autoFocus
                            autoComplete="off"
                        />
                        <TextField
                            variant="outlined"
                            margin="normal"
                            required
                            fullWidth
                            label="登录ID"
                            name="loginId"
                            value={form.loginId || ''}
                            onChange={handleChange}
                            inputProps={{
                                minLength: 5,
                            }}
                            placeholder="至少 5 个字符"
                            autoComplete="off"
                        />
                        <TextField
                            variant="outlined"
                            margin="normal"
                            required
                            fullWidth
                            label="密码"
                            name="password"
                            type="password"
                            value={form.password || ''}
                            onChange={handleChange}
                            inputProps={{
                                minLength: 6,
                            }}
                            placeholder="至少 6 个字符"
                            autoComplete="new-password"
                        />

                        {form.role === 'PRINCIPAL' &&
                            <TextField
                                variant="outlined"
                                margin="normal"
                                required
                                fullWidth
                                label='你的学校名称'
                                name="school"
                                value={form.school || ''}
                                onChange={handleChange}
                                autoComplete="off"
                            />
                        }

                        <LoadingButton
                            type="submit"
                            disabled={loading}
                            fullWidth
                            variant="contained"
                            color="primary"
                            className="submit"
                            size="large"
                            sx={{height: "56px", marginTop: "16px"}}
                            loadingIndicator={<CircularProgress color="inherit" size={32}/>}
                            loading={loading}
                        >
                            注册
                        </LoadingButton>
                    </form>
                </Box>
            </Box>
        </Container>
    </>);
}

export default RegisterPage;
